﻿using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace FirstDemo.Hubs
{
    public class ChatHub : Hub
    {
        private IList<string> userList = UserInfo.userList;
        private readonly static Dictionary<string, string> _connections = new Dictionary<string, string>();
        /// <summary>
        /// 发送给所有人
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task SendMessage(string user, string message)
        {
            await Clients.All.SendAsync("ReceiveMessage", user, message);
        }

        /// <summary>
        /// 发送给指定用户
        /// </summary>
        /// <param name="user"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task SendOneMessage(string userId, string user, string message)
        {
            await Clients.Client(_connections[userId]).SendAsync("ReceiveMessage" , user, message);
        }

        public void SendLogin(string userId)
        {
            if (!userList.Contains(userId))
            {
                userList.Add(userId);
                //这里便是将用户id和姓名联系起来
                _connections.Add(userId, Context.ConnectionId);
            }
            else
            {
                //每次登陆id会发生变化
                _connections[userId] = Context.ConnectionId;
            }
            //新用户上线，服务器广播该用户名
            //Clients.All.loginUser(userList);
        }
    }
}
